import Mock from "mockjs"

// Mock configuration
Mock.setup({
  timeout: "200-600",
})

// Generate mock data
const posts = []
const categories = [
  { id: 1, name: "技术", count: 5 },
  { id: 2, name: "生活", count: 3 },
  { id: 3, name: "设计", count: 2 },
  { id: 4, name: "其他", count: 1 },
]

// Generate sample posts
for (let i = 1; i <= 10; i++) {
  posts.push({
    id: i.toString(),
    title: `博客文章 ${i}`,
    author: "Admin",
    category: i % 4 === 0 ? "其他" : i % 3 === 0 ? "设计" : i % 2 === 0 ? "生活" : "技术",
    summary: `这是博客文章 ${i} 的摘要，简要介绍了文章的主要内容和观点。`,
    content: `<p>这是博客文章 ${i} 的详细内容。</p>
              <p>使用 Vue 3 的 Composition API 可以很方便地组织代码逻辑，提高代码的可读性和可维护性。</p>
              <h2>标题示例</h2>
              <p>这里是一些示例内容，展示博客文章的格式。可以包含<strong>加粗</strong>、<em>斜体</em>等样式。</p>
              <p>同时也可以包含代码示例：</p>
              <pre>const app = createApp(App)
app.use(router)
app.mount('#app')</pre>
              <p>还可以包含列表：</p>
              <ul>
                <li>列表项 1</li>
                <li>列表项 2</li>
                <li>列表项 3</li>
              </ul>`,
    createdAt: new Date(Date.now() - i * 86400000).toISOString(),
    comments: Array.from({ length: Math.floor(Math.random() * 5) }, (_, j) => ({
      name: `用户${j + 1}`,
      content: `这是对文章 ${i} 的评论 ${j + 1}，分享了对文章的看法和建议。`,
      date: new Date(Date.now() - (i + j) * 3600000).toISOString(),
    })),
  })
}

// API mock endpoints
// Get paginated posts
Mock.mock(/\/api\/posts(\?.+)?$/, "get", (options) => {
  const url = new URL(`http://example.com${options.url}`)
  const page = Number.parseInt(url.searchParams.get("page") || "1")
  const pageSize = Number.parseInt(url.searchParams.get("pageSize") || "5")

  const start = (page - 1) * pageSize
  const end = start + pageSize

  return {
    posts: posts.slice(start, end),
    total: posts.length,
    currentPage: page,
    pageSize: pageSize,
  }
})

// Get all posts (for admin)
Mock.mock("/api/posts/all", "get", () => {
  return posts
})

// Get single post
Mock.mock(/\/api\/posts\/\d+$/, "get", (options) => {
  const id = options.url.match(/\/api\/posts\/(\d+)/)[1]
  return posts.find((post) => post.id === id) || null
})

// Create new post
Mock.mock("/api/posts", "post", (options) => {
  const newPost = JSON.parse(options.body)
  newPost.id = (posts.length + 1).toString()
  posts.unshift(newPost)
  return { success: true, post: newPost }
})

// Update post
Mock.mock(/\/api\/posts\/\d+$/, "put", (options) => {
  const id = options.url.match(/\/api\/posts\/(\d+)/)[1]
  const updatedPost = JSON.parse(options.body)

  const index = posts.findIndex((post) => post.id === id)
  if (index !== -1) {
    posts[index] = { ...posts[index], ...updatedPost }
    return { success: true, post: posts[index] }
  }

  return { success: false, message: "Post not found" }
})

// Delete post
Mock.mock(/\/api\/posts\/\d+$/, "delete", (options) => {
  const id = options.url.match(/\/api\/posts\/(\d+)/)[1]
  const index = posts.findIndex((post) => post.id === id)

  if (index !== -1) {
    posts.splice(index, 1)
    return { success: true }
  }

  return { success: false, message: "Post not found" }
})

// Add comment to a post
Mock.mock(/\/api\/posts\/\d+\/comments$/, "post", (options) => {
  const id = options.url.match(/\/api\/posts\/(\d+)\/comments/)[1]
  const comment = JSON.parse(options.body)

  const post = posts.find((post) => post.id === id)
  if (post) {
    if (!post.comments) {
      post.comments = []
    }
    post.comments.push(comment)
    return { success: true, comment }
  }

  return { success: false, message: "Post not found" }
})

// Get categories
Mock.mock("/api/categories", "get", () => {
  return categories
})

// Login
Mock.mock("/api/login", "post", (options) => {
  const { username, password } = JSON.parse(options.body)

  // Simple authentication for demo
  if (username === "admin" && password === "password") {
    return {
      success: true,
      token: "mock-jwt-token",
      user: {
        id: 1,
        name: "Admin",
        username: "admin",
        role: "admin",
      },
    }
  }

  return {
    success: false,
    message: "用户名或密码错误",
  }
})

